var express = require('express');
var router = express.Router();
// 导入MySQL模块
var mysql = require('mysql');
var dbConfig = require('../DB/dbConf');
// 使用DBConfig.js的配置信息创建一个MySQL连接池
var pool = mysql.createPool( dbConfig);
//导入uuid
var uuid=require('node-uuid');

//用户登录
router.post('/userlogin',function(req,res,next){
  pool.getConnection((err,connection)=>{
    connection.query('SELECT uid,status FROM user WHERE username=? and password=?',[req.body.username,req.body.password],(err,resutls)=>{
      if (err) throw err;
      if(resutls.length>0){
        if(resutls[0].status==1){
          //存入session
          req.session.userid=resutls[0].uid;
        }
        res.json({'status':resutls[0].status,'uid':resutls[0].uid});
      }else{
        res.json({'status':'0'});
      }
      connection.release();
    });
  });
});

//用户注册
router.post('/userreg',function(req,res,next){
  pool.getConnection((err,connection)=>{
    connection.query('INSERT INTO user(uid,username,password) VALUES(?,?,?)',[uuid.v1(),req.body.uname,req.body.password],(err,resutls)=>{
        if (err) throw err;
        (resutls.affectedRows == 1)?res.json({'msg':'1'}):res.json({'msg':'0'});
    });
    connection.release();
  });
});

//管理员登录
router.post('/adminlogin', function (req, res, next) {
  pool.getConnection((err, connection) => {
    console.log(req.ip);
    console.log(req.body);
    connection.query(userSQL.loginCheck, [req.body.username, req.body.password], (err, resutls) => {
      if (err) throw err;
      if (resutls.length > 0) {
        //存入session
        req.session.username = req.body.username;
        res.send('1');
      } else {
        res.send('0');
      }
      connection.release();
    });
  });
});
module.exports = router;